package meijuli.com.join51.business.data;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author Scott Smith  @Date 2016年08月16/8/24日 20:22
 */
public class DownloaderImpl extends Downloader {
    private Downloader.OnDownloadListener onDownloadListener = null;
    private DownloadHandler mDownLoadHandler = null;
    private Looper mDownloadLooper = null;
    private final String KEY_PATH = "video_url";
    private final String KEY_FILE_NAME = "file_name";
    private final String KEY_URL = "url";
    private Handler mHandler = new Handler(Looper.getMainLooper());

    DownloaderImpl(Downloader.OnDownloadListener onDownloadListener) {
        this.onDownloadListener = onDownloadListener;

        HandlerThread handlerThread = new HandlerThread("Downloader");
        handlerThread.start();

        mDownloadLooper = handlerThread.getLooper();
        mDownLoadHandler = new DownloadHandler(mDownloadLooper);
    }

    @Override
    public void download(String url, String path, String fileName) {
        Message message = mDownLoadHandler.obtainMessage();
        Bundle data = new Bundle();
        data.putString(KEY_URL, url);
        data.putString(KEY_PATH, path);
        data.putString(KEY_FILE_NAME, fileName);
        message.setData(data);
        message.sendToTarget();
    }

    @Override
    public void removeListener() {
        onDownloadListener = null;
    }

    private class DownloadHandler extends Handler {
        public DownloadHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            Bundle data = msg.getData();
            final String url = data.getString(KEY_URL);
            final String path = data.getString(KEY_PATH);
            final String fileName = data.getString(KEY_FILE_NAME);
            File file = null;

            try {
                URL URL = new URL(url);
                final HttpURLConnection connection = (HttpURLConnection) URL.openConnection();
                connection.setRequestMethod("GET");
                connection.setDoInput(true);
                connection.setConnectTimeout(8 * 1000);
                connection.setReadTimeout(8 * 1000);

                if (200 == connection.getResponseCode()) {
                    final int content_length = connection.getContentLength();
                    InputStream inputStream = connection.getInputStream();
                    byte[] buffer = new byte[1024 * 20];
                    // 下载开始
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            onDownloadListener.onDownloadStarted(url, path, fileName);
                        }
                    });

                    int length = inputStream.read(buffer);
                    int currSize = length;
                    file = new File(path + "/" + fileName);
                    if (!file.getParentFile().exists()) {
                        if (file.getParentFile().mkdirs()) {
                            file.createNewFile();
                        }
                    } else {
                        if (!file.exists()) {
                            file.createNewFile();
                        }
                    }
                    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
                    while (length != -1) {
                        outputStream.write(buffer, 0, length);
                        final int currSizeTemp = currSize;
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (null != onDownloadListener) {
                                    onDownloadListener.onDownloading(url, content_length, currSizeTemp);
                                }
                            }
                        });
                        length = inputStream.read(buffer);
                        currSize += length;
                    }
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (null != onDownloadListener) {
                                onDownloadListener.onDownloadFinished(url, path, fileName);
                            }
                        }
                    });

                    outputStream.flush();
                    inputStream.close();
                } else {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (null != onDownloadListener) {
                                try {
                                    onDownloadListener.onDownloadErr(connection.getResponseCode(), url, connection.getResponseMessage());
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
                }
            } catch (final Exception e) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (null != onDownloadListener) {
                            onDownloadListener.onDownloadErr(-1, url, e.getMessage());
                        }
                    }
                });
            }
        }
    }

    @Override
    public void quit() {
        removeListener();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            mDownloadLooper.quitSafely();
        } else {
            mDownloadLooper.quit();
        }
    }
}